<?php

use addons\kzvote\library\WechatService;

if (!function_exists('kzvote_getConfig')) {
    /**
     * 获取配置
     * @param string $field 配置组名
     * @param string $key 字段
     * @param string $default 字段默认值
     * @param boolean $refresh 是否刷新缓存
     * @return mixed
     */
    function kzvote_getConfig(string $field, $key = '', $default = '', $refresh = true)
    {
        $config = \think\Cache::get($field);

        if (!$config || $refresh) {
            $config = \think\Db::name('kzvote_config')->where('1=1')->order('id')->limit(1)->value($field);

            if (!$config) {
                return null;
            }

            $config = json_decode($config, true);
            //存入缓存
            \think\Cache::set($field, $config);
        }

        if ($key) {
            return $config[$key] ?? $default;
        }

        return $config;
    }
}

if (!function_exists('kzvote_postCurl')) {
    /**
     * post请求
     * @param        $url
     * @param string $data
     * @param string $type
     * @return bool|string
     */
    function kzvote_postCurl($url, $data = '', $type = 'json')
    {
        if ($type == 'json') {
            $data = json_encode($data); //对数组进行json编码
            $header = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $res = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Error+' . curl_error($curl);
        }
        curl_close($curl);
        return $res;
    }
}

if (!function_exists('kzvote_generate_no')) {
    /**
     * 根据时间生成编号
     * @return string
     */
    function kzvote_generate_no($pre = '')
    {
        $date = date('YmdHis', time());
        $u_timestamp = microtime(true);
        $timestamp = floor($u_timestamp);
        $milliseconds = round(($u_timestamp - $timestamp) * 100); // 改这里的数值控制毫秒位数
        return $pre . $date . date(preg_replace('`(?<!\\\\)u`', $milliseconds, 'u'), $timestamp);
    }
}
if (!function_exists('kzvote_hex2rgba')) {
    /**
     * 颜色代码转RGB
     */
    function kzvote_hex2rgba($color, $opacity = false, $raw = false)
    {
        $default = 'rgb(0,0,0)';
        //Return default if no color provided
        if (empty($color)) {
            return $default;
        }

        if ($color[0] == '#') {
            $color = substr($color, 1);
        }
        //Check if color has 6 or 3 characters and get values
        if (strlen($color) == 6) {
            $hex = array($color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5]);
        } elseif (strlen($color) == 3) {
            $hex = array($color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2]);
        } else {
            return $default;
        }

        //Convert hexadec to rgb
        $rgb = array_map('hexdec', $hex);

        if ($raw) {
            if ($opacity) {
                if (abs($opacity) > 1) {
                    $opacity = 1.0;
                }

                array_push($rgb, $opacity);
            }
            $output = $rgb;
        } else {
            //Check if opacity is set(rgba or rgb)
            if ($opacity) {
                if (abs($opacity) > 1) {
                    $opacity = 1.0;
                }

                $output = 'rgba(' . implode(",", $rgb) . ',' . $opacity . ')';
            } else {
                $output = 'rgb(' . implode(",", $rgb) . ')';
            }
        }

        return $output;
    }
}

if (!function_exists('kzvote_getOpenid')) {
    /**
     * 获取配置
     * @param string  $field   配置组名
     * @param string  $key     字段
     * @param string  $default 字段默认值
     * @param boolean $refresh 是否刷新缓存
     * @return mixed
     */
    function kzvote_getOpenid($user_id,$platform)
    {
        $openidModel = new app\common\model\kzvote\Openid();
        $data = $openidModel->where('user_id',$user_id)->where('unionid','<>','')->find();
        if ($data){
            return $platform == 'wxapp' ? $data['openid'] : $data['open_id'];
        }else{
            $openid = $openidModel->where('user_id',$user_id)->value($platform == 'wxapp'?'openid':'open_id');
            return $openid;
        }
    }
}
if (!function_exists('kzvote_qrCode')) {
    /**
     * 生成小程序码
     * @param \think\Model  $model   对应模型
     * @param string  $scene     参数
     * @param string  $page   路径
     * @return mixed
     */
    function kzvote_qrCode($model, $scene, $page)
    {
        try {
            if (!$model['er_code']) {
                $service = new WechatService();
                $app = $service->getMiniApp();
                if($scene)
                    $response = $app->app_code->getUnlimit($scene,['page'=>$page,'is_hyaline'=>true]);
                else
                    $response = $app->app_code->get($page);

                if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                    $filename = $response->saveAs(ROOT_PATH.'public/uploads/kzvote/', md5(rand(100000,999999).'_'.$scene).'.png');
                    $filePath = '/uploads/kzvote/'.$filename;
                    $model->er_code = $filePath;
                    $model->save();
                    return $filename;
                }
                return null;
            }
        }catch (\Exception $e){
            return null;
        }
    }
}
